<?php
namespace Shopmanage\Controller;
use Think\Controller;
class GiftsController extends ExtendController {
	public function __construct() {
		parent::__construct();
		$this->assign("current","shopgift");
	}
	public function index(){
	// 奖品设置
		Vendor('Page');
		$type=(int)I("get.type");
		$ctp=I("get.ctp");
		$ctp=$ctp?$ctp:"all";
		$tools = C("GFT_TYPE");
		if($ctp=="all"||!$ctp){
			$where="`sid`=".$this->sid;
		}else{
			$where="`sid`=".$this->sid." AND type=".$tools[$ctp]["id"];
		}
		if($type){
			$where .= " AND `status`=9";
		}else{
			$where .= " AND `status`<>9";
		}
		$where .=" AND `event_id`=0";
		
		$GIFTS = D("EventsGifts");
		$GIFTS->wherestr = $where;
		$GIFTS->rollPage = $this->rollPage;
		$GIFTS->listRows = $this->listRows;
		$GIFTS->getgifts(); 
		$data = $GIFTS->gifts;
		$Page = $GIFTS->Page;
		// $E = M("EventsGifts");
		// $total = $E->where($where)->count();
		// $Page = new \Page($total,$this->listRows);
		// $Page->rollPage=$this->rollPage;
		// $show = $Page->show();
		// $data = $E->where($where)
				  // ->limit($Page->firstRow.','.$Page->listRows)
				  // ->getField("`id`,`type`,`status`,`level`,`name`,`details`,`price`,`probability`,`isshow`,`quantity`,`pic_url`,`num_iids`,`event_id`,`promoid`,`tagid`,`sid`");
		// foreach($data as $k=>$gift){
			// $data[$k]["probability"]=$data[$k]["probability"]."%";
			// $data[$k]["level"]=getlevel($data[$k]["level"]);
			// foreach($tools as $tool){
				// if($data[$k]["type"]==$tool["id"]){
					// $data[$k]["type"]=$tool["name"];
				// }
			// }
		// }
		$info["type"]="warning";
		$info["msg"]="注意！概率总和不要超过100%。如果超过100%，系统会自动按照100%重算各奖品概率。";
		$this->assign('admin',"gifts");
		$this->assign('totalpg',(int)$Page->totalPages);
		$this->assign('curpg',$Page->nowPage);
		$this->assign('page',$Page->show());
		$this->assign('ctp',$ctp);
		$this->assign('tools',$tools);
		$this->assign('data',$data);
		$this->assign('type',$type);
		$this->assign('info',$info);
		$this->assign('title','奖品管理');
		$this->display();
	}
	public function add(){
		$ctp=I("get.ctp");
		$ctp = $ctp?$ctp:"item";
		$tools = Array(
			"zailai"=>array("name"=>"抽奖次数","status"=>1,"id"=>7,"tip"=>"填写增加次数"),
			"jifen"=>array("name"=>"积分","status"=>1,"id"=>10,"tip"=>"填写积分数量"),
		);
		$this->assign('tools',$tools);
		$this->assign('edit_gifts',false);
		$this->assign('title','添加奖品');
		$this->display();
	}
	public function save(){
		$gtitle = I("post.gtitle");
		$imgurl = I("post.imgurl");
		$prob = I("post.prob");
		$count = I("post.count");
		$type = I("post.type");
		$numiid = I("post.numiid");
		$text = I("post.text");
		$id = I("post.id");
		$price = I("post.price");
		$level = I("post.level");
		$tagid = I("post.tagid");
		$promid = I("post.promid");
		
		foreach($gtitle as $k=>$v){
			$data=array();
			$data["level"]=$level[$k];
			$data["name"]=$gtitle[$k];
			$data["type"]=$type[$k];
			$data["details"]=$text[$k];
			$data["probability"]=$prob[$k]*100;
			$data["quantity"]=$count[$k];
			$data["quantity_initial"]=$count[$k];
			$data["pic_url"]=$imgurl[$k];
			$data["num_iids"]=$numiid[$k];
			$data["sid"]=$this->sid;
			$data["event_id"]='0';//
			$data["price"]=$price[$k];
			$data["status"]=0;
			$data["promoid"]=$promid[$k];
			$data["tagid"]=$tagid[$k];
			$gifts[]=$data;
			
			$Gift = M("EventsGifts");
			if(!$cacheService){$cacheService = D("Shopmanage/Catche");}
			if($cacheService->get($this->safe."edit_gifts")){
				if(!$id[$k]){
					$re = $Gift->add($data);
					$msg="添加"; 
					if($re&&$data["type"]==4){
						$km=array();
						$km["status"]=8;
						$km["giftid"]=$re;
						$KM = M("EventsGiftsKm");
						$KM->where("`tscode`=".$data["num_iids"]." AND `sid`=".$this->sid)->save($km);
						$kmcount["quantity"] = $KM->where("`tscode`=".$data["num_iids"]." AND `sid`=".$this->sid." AND `status`=8")->count("`id`");
						$Gift->where("`id`=".$re)->save($kmcount);
					}
				}else{
					if($data["type"]==4){
						$KM = M("EventsGiftsKm");
						$oldkm = $Gift->where("`id`=".(int)$id[$k]." AND `sid`=".$this->sid)->getField("num_iids");
						if($oldkm){
						$km=array();
						$km["status"]=1;
						$KM->where("`tscode`=".$oldkm." AND `sid`=".$this->sid." AND `status`<=8")->save($km);
						}
					}
					$re = $Gift->where("`id`=".(int)$id[$k]." AND `sid`=".$this->sid)->save($data);
					$msg="修改";
					if($re&&$data["type"]==4&&$data["num_iids"]){
						$km["status"]=8;
						$km["giftid"]=(int)$id[$k];
						$KM = M("EventsGiftsKm");
						$KM->where("`tscode`=".$data["num_iids"]." AND `sid`=".$this->sid)->save($km);
						$kmcount["quantity"] = $KM->where("`tscode`=".$data["num_iids"]." AND `sid`=".$this->sid." AND `status`=8")->count("`id`");
						$Gift->where("`id`=".$id[$k])->save($kmcount);
					}
					$edit_gifts[$id[$k]]=(int)$id[$k];
				}
			}else{
				$re = $Gift->add($data);
				$msg="添加";
				if($re&&$data["type"]==4){
					$km["status"]=8;
					$km["giftid"]=$re;
					$KM = M("EventsGiftsKm");
					$KM->where("`tscode`=".$data["num_iids"])->save($km);
					$kmcount["quantity"] = $KM->where("`tscode`=".$data["num_iids"]." AND `sid`=".$this->sid." AND `status`=8")->count("`id`");
					$Gift->where("`id`=".$re)->save($kmcount);
				}
			}
			if($re){
				$info["type"]="success";
				$info["msg"].=$msg.$gtitle[$k]."成功！<br />";
			}else{
				$info["type"]="error";
				$info["msg"].=$msg."奖品“".$gtitle[$k]."”失败！您可能未做任何更改<br />";
			}
		}
		$this->success($info["msg"],'/?m=shopmanage&c=gifts');
	}
	public function edit(){
		$id=(int)I("get.id");
		$ids = I("get.ids");
		$Gift = M("EventsGifts");
		$fields = "`id`,`type`,`level`,`name`,`details`,`price`,`probability`,`isshow`,`quantity`,`pic_url`,`num_iids`,`event_id`,`promoid`,`tagid`,`sid`";
		if($id){
			$gifts = $Gift->where("`id`=".$id)->getField($fields);
		}
		if($ids){
			$ids = explode("|",$ids);
			foreach($ids as $i){
				$i=(int)$i;
				if(is_int($i)){
					$strid[]=$i;
				}
			}
		}
		if($strid){
			$gifts = $Gift->where("`id` IN (".implode(",",$strid).")")->getField($fields);
		}
		
		foreach($gifts as $k=>$gift){
			$gifts[$k]["probability"]=$gifts[$k]["probability"]/100;
		}
		$gift_type = Array ( "zailai" => Array ( "name" => "抽奖次数", "status" => 1, "id" => 7, "tip" => "填写增加次数" ),
							 "jifen" => Array ( "name" => "积分", "status" => 1, "id" => 10, "tip" =>"填写积分数量" ),
							 "rongyu" => Array ( "name" => "荣誉奖章", "status" => 1, "id" => 11, "tip" => "输入奖章" ));
		if(!$cacheService){$cacheService = D("Shopmanage/Catche");}
		$cacheService->set($this->safe."edit_gifts",$gifts,3000);
		$this->assign("gifts",$gifts);
		$this->assign('tools',$gift_type);
		$this->assign('title','修改奖品');
		$this->display("add");
	}
	public function remove(){
		$id=(int)I("get.id");
		$Gift = M("EventsGifts");
		if($Gift->where("`id`=".$id." AND `sid`=".$this->sid)->setField("status",9)){
			$KM=M("EventsGiftsKm");
			$KM->where("`giftid`=".$id." AND `status`=8 AND `sid`=".$this->sid)->setField("status",2);
			$this->success("删除成功！",'/?m=shopmanage&c=gifts');
		}else{
			$this->success("删除失败！",'/?m=shopmanage&c=gifts');
		}
	}
	public function getgifts(){
		$Gift = M("EventsGifts");
		$data = $Gift->where("`sid`=".$this->sid." AND `quantity`>0 AND `status`<>9")->getField("id,name,level,quantity,type,tagid",true,true);
		foreach($data as $k=>$gift){
			$data[$k]["level"]=getlevel($data[$k]["level"]);
		}
		$re["gifts"]=$data;
		$this->ajaxReturn($re);
	}
	public function msend(){
		$usernick = I("get.nick");
		$giftid = I("get.gift");
		$gifttp = I("get.type");
		$gifttagid = I("get.tagid");
		
		$User = D("Shopmodule/User");
		$User->usernick=$this->usernick;
		$User->sid=$this->sid;
		$User->getShopUser();
		
		$UG = D("UsersGifts");
		$UG->sid=$this->sid;
		$UG->UserSPID=$User->suid;
		$UG->giftid=$giftid;
		$UG->gifttp=$gifttp;
		$UG->gifttagid=$gifttagid;
		if(C("TAE")){
			$UG->usernick=urldecode_utf8($usernick);
		}else{
			$UG->usernick=urldecode($usernick);
		}
		$UG->getway='shoud';
		$UG->send_gift();
		$reda = $UG->status;
		// 以下代码已封装
		// $usernick = urldecode_utf8($usernick);
		// $User = M("User");
		// $this->UserUZID = $User->where("`usernick`='".$usernick."'")->getField("id");
		// if(!$this->UserUZID){
			// $data = array();
			// $data["usernick"]=$usernick;
			// $data["jointime"]=date("Y-m-d H:i:s",time());
			// $this->UserUZID = $User->add($data);
		// }
		// $ShopUser = M("ShopUsers");
		// $this->UserSPID = $ShopUser->where("`userid`=".$this->UserUZID)->getField("id");
		// if(!$this->UserSPID){
			// $data = array();
			// $data["sid"]=$this->sid;
			// $data["userid"]=$this->UserUZID;
			// $data["addtime"]=date("Y-m-d H:i:s",time());
			// $this->UserSPID = $ShopUser->add($data);
		// }
		// $UG = D("UsersGifts");
		// $this->ugid = $UG->where("`giftid`=".$giftid." AND `uzuid`=".$this->UserSPID)->getField("`id`");
		
		// if($gifttp==7){
			// // 再来一次奖品的处理
			// $GFT = M("EventsGifts");
			// $score_ingift = $GFT->where("`id`=".$giftid)->getField("num_iids"); //取出要增加的次数
			// $U = D("EventsUsers");
			// $Uscore = $U->where("`uzuid`='".$this->UserSPID."' AND `sid`=".$this->sid." AND `eventid`=0")->limit(1)->getField("id");//echo $U->_sql();
			// $UG->execute("update `sm_events_users` set `score` = `score`+".$score_ingift." WHERE `id` = ".$Uscore);
		// }
		// if($gifttp==4){
			// // 中得卡密要保存卡密id，不论是否已中奖都新增
			// $KM = M("EventsGiftsKm");
			// $kamiid = $KM->where("`giftid`=".$giftid." AND `sid`=".$this->sid." AND `status`=8")->limit(1)->getField("`id`");
			// if($kamiid){
				// $data["kamiid"]=$kamiid;
				// // $data["cardno"]=$kami["cardno"];
				// // $data["secret"]=$kami["secret"];
				// $kmsv["status"]=9;
				// $kmsv["shopuid"]=$this->UserSPID;
				// $KM->where("`id`=".$kamiid)->save($kmsv);
			// }else{
				// $this->gifts[$re]["cardno"]="没有卡号";
				// $this->gifts[$re]["secret"]="";
			// }
		// }
		// if($gifttp==5){
			// // 中得折扣类型奖品，远程加载贴标签动作
			// $tagid = $gifttagid;
			// $ts = time();
			// $sign=md5(C('TOOL_KEY').$ts.($usernick).$tagid.$this->sid.$action.C('TOOL_SECRET')); 
			// $r = $fetchService->fetchByGet("http://hg.itianshan.com/?m=Shopmodule&a=adduser&shopid=".$this->sid."&usernick=".urlencode_utf8($this->usernick)."&tagid=".$tagid."&ts=".$ts."&sign=".$sign);
		// }
		// // if(!$this->ugid){ 
		// // 不论是否已有该奖品都新增一个奖品
			// $data = array();
			// $data["uzuid"]=$this->UserSPID;
			// $data["giftid"]=$giftid;
			// $data["sid"]=$this->sid;
			// $data["actiontime"]=date("Y-m-d H:i:s",time());
			
			// if($gifttp<>1){
				// $data["status"]=1;
			// }
			// $reda["ugid"] = $UG->add($data);
			// $reda["quant"] = $UG->execute("update `sm_events_gifts` set `quantity` = IF(`quantity`<1, 0, `quantity`-1) WHERE `id` = ".$giftid);
			// if($reda["ugid"]&&$reda["quant"]){
				// $reda["status"]=1;
			// }else{
				// $reda["status"]=0;
			// }
		// // }
		$this->ajaxReturn($reda);
	}
}